package com.ebo.synframework.nettybase.protoPool;

import java.util.concurrent.atomic.AtomicInteger;

import com.ebo.synframework.nettybase.codec.ProtoFactory;
import com.google.protobuf.Message.Builder;


public class ReusedProtoBuilder {
	
	private Builder builder;
	
	private volatile ProtoBuilderPool pool;
	
	private AtomicInteger releaseCounter;
	
	public ReusedProtoBuilder(String protoName, ProtoBuilderPool pool){
		this.builder = ProtoFactory.getProtoInstance(protoName).newBuilderForType();
		this.pool = pool;
		this.releaseCounter = new AtomicInteger(1);
	}
	
	public void resetReleaseCounter() {
		this.releaseCounter.set(1);
	}
	
	public void setReleaseCounter(int num) {
		this.releaseCounter.set(num);
	}
	
	public void release(){
		int counter = this.releaseCounter.decrementAndGet();
		if(counter == 0) {
			builder.clear();
			pool.release(this);
		}
	}
	
	public Builder getBuilder(){
		return builder;
	}
	
	public ProtoBuilderPool getPool(){
		return pool;
	}
}
